<template>
    <el-card class="mt16">
        <!-- 提示 -->
        <el-alert :closable="false" effect="dark" title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon />
        <!-- 选择商品分类 -->
        <el-row class="mt16">
            <el-col :span="3">
                <span>选择商品分类:</span>
            </el-col>
            <el-col :span="20">
                <el-cascader v-model="checkedArr" :options="goodsCateList" :props="defaultProps" @change="handleChange" />
            </el-col>
        </el-row>
        <!-- 切换分类参数 动态|静态 -->
        <el-tabs class="mt16" type="border-card" v-model="activeName" @tab-change="getActiveName">
            <!-- 动态参数tab -->
            <el-tab-pane label="动态参数" name="many">
                <!-- 动态参数添加按钮 -->
                <el-row>
                    <el-col>
                        <el-button :disabled="isOk" type="primary" @click="addParamsDia">添加参数</el-button>
                    </el-col>
                </el-row>

                <!-- 渲染动态参数表格 -->
                <el-table :data="manyParamsData" border class="mt16" row-key="attr_id">
                    <el-table-column label="" type="expand">
                        <template #default="scope">
                            <div class="pad16" v-if="scope.row.attr_vals.length > 0">
                                <!-- <el-tag style="margin:10px" closable v-for="(item, index) in scope.row.attr_vals"
                                    :key="index">{{
                                        item
                                    }}</el-tag> -->

                                <el-tag style="margin:10px" closable v-for="(item, index) in scope.row.attr_vals"
                                    :key="index" class="mx-1" @close="handleClose(index, scope.row)">
                                    {{ item }}
                                </el-tag>
                                <el-input v-if="scope.row.inputVisible" ref="InputRef" v-model="scope.row.inputValue"
                                    class="inputParams" size="small" @keyup.enter="handleInputConfirm(scope.row)"
                                    @blur="handleInputConfirm(scope.row)" />
                                <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput(scope.row)">
                                    + New Tag
                                </el-button>
                            </div>
                            <div class="pad16" v-else>暂无参数</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="#" type="index"></el-table-column>
                    <el-table-column label="参数名" prop="attr_name"></el-table-column>
                    <el-table-column label="操作">
                        <template #default="scope">
                            <div>
                                <el-button type="primary" :icon="Edit" size="small">编辑</el-button>
                                <el-button type="danger" :icon="Delete" size="small">删除</el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>

            </el-tab-pane>
            <!-- 静态参数tab -->
            <el-tab-pane label="静态属性" name="only">222</el-tab-pane>
        </el-tabs>
    </el-card>

    <!-- 添加参数对话框 -->
    <el-dialog v-model="isAddParams" title="添加动态参数" width="30%" :before-close="handleClose">
        <el-form :model="addParamsObj">
            <!-- <el-form-item>
                <el-input v-model=""></el-input>
            </el-form-item> -->
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="isAddParams = false">Cancel</el-button>
                <el-button type="primary" @click="isAddParamsOk">
                    Confirm
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { computed, nextTick, onMounted, reactive, ref } from 'vue'
import type { CascaderProps } from 'element-plus'
import * as API from '@/http/api'
import { ElMessage } from 'element-plus'
import { Edit, Delete } from '@element-plus/icons-vue'

const addParamsObj = reactive({

})

//是否显示添加对话框
const isAddParams = ref(false)

//打开添加参数对话框
const addParamsDia = () => {
    isAddParams.value = true
}

//确定添加参数
const isAddParamsOk = () => {

}


//敲回车或失焦时添加数据并且隐藏输入框
const handleInputConfirm = async (row: any) => {
    if (row.inputValue.trim().length > 0) {
        //将输入的参数添加到数组中
        row.attr_vals.push(row.inputValue.trim())
    }

    //调用参数更新接口
    await API.updateGoodsParamsApi(row.cat_id, row.attr_id, {
        attr_name: row.attr_name,
        attr_sel: activeName.value,
        attr_vals: row.attr_vals.length > 0 ? row.attr_vals.join(',') : ''
    })

    //清空inputvalue
    row.inputValue = ''
    //隐藏输入框并切换按钮
    row.inputVisible = false;
}

//删除参数tag
const handleClose = async (i: number, row: any) => {
    console.log(i)
    row.attr_vals.splice(i, 1)
    //同步更新到后台
    //调用参数更新接口
    await API.updateGoodsParamsApi(row.cat_id, row.attr_id, {
        attr_name: row.attr_name,
        attr_sel: activeName.value,
        attr_vals: row.attr_vals.length > 0 ? row.attr_vals.join(',') : ''
    })

}

const InputRef = ref()
//点击按钮，显示输入框并获取焦点
const showInput = async (row: any) => {
    row.inputVisible = true
    //等待DOM加载完成
    await nextTick()
    //让输入框获得焦点
    InputRef.value!.input!.focus()
}

//动态参数数组
const manyParamsData = ref([])

//按钮是否禁用  true:禁用  false:可用
const isOk = computed(() => !(checkedArr.value.length === 3))
//当前商品分类ID
const currentCateId = computed(() => checkedArr.value[checkedArr.value.length - 1])

//选中的分类id数组
const checkedArr = ref<number[]>([])

//tab当前active
const activeName = ref('many')
const getActiveName = () => {
    console.log(activeName.value)
}

//商品分类数组
const goodsCateList = ref([])

//级联选择器配置项
const defaultProps = reactive<CascaderProps>({
    label: 'cat_name',
    value: 'cat_id',
    expandTrigger: "hover",
    children: 'children'
})

//级联选择器改变后触发
const handleChange = () => {

    if (checkedArr.value.length !== 3) {
        //如果不够三级显示提示
        ElMessage({
            message: '您选择的级别不够三级，请重新选择',
            type: 'error'
        })
        //如果不够三级清空动态参数表格数据
        manyParamsData.value = []

        return
    }

    //否则的话调用参数列表进行展示
    getGoodsParamsList()

}

//获取商品参数列表方法
const getGoodsParamsList = async () => {

    if (activeName.value === 'many') {
        //调用动态参数接口
        const res = await API.getGoodsParamsListApi(currentCateId.value, 'many')

        res.data.forEach((item: any) => {
            //item.attr_vals= 如果是空 ？[]:转换
            item.attr_vals = item.attr_vals.length !== 0 ? item.attr_vals.split(',') : []
            item.inputValue = ''
            item.inputVisible = false
            console.log('商品动态参数：', res)
        })
        manyParamsData.value = res.data


    } else if (activeName.value === 'only') {
        //调用静态参数
    }


}

onMounted(() => {
    getGoodsCateList()
})

//商品分类列表
const getGoodsCateList = async () => {
    //调用商品分类接口
    const res = await API.getGoodsCateListApi({ type: 3 })
    console.log('三级分类:', res)
    goodsCateList.value = res.data
}

</script>

<style scoped>
@import "@/assets/public.css";

.inputParams {
    width: 100px;
}
</style>